package com.laobiao.file_netty_lib.netty.server;

import java.util.logging.Logger;

import com.laobiao.file_netty_lib.content.LoggerUtil;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;

public class FileServer {
	private static final Logger logger=LoggerUtil.getLogger(FileServer.class);
	private ChannelFuture serverFuture;
	/**
	 * 连接管理组
	 */
	private EventLoopGroup bossGroup;
	/**
	 * 工作组
	 */
	private EventLoopGroup workerGroup;
	/**
	 * netty引导
	 */
	private ServerBootstrap serverBootstrap;
	/**
	 * 初始化文件服务器
	 * @param port 服务端口
	 * @param maxBacklog 最大事务处理队列长度
	 * @param localBaseDirPath 本地文件存储基础目录
	 */
	public FileServer(int port ,int maxBacklog,String localBaseDirPath) {
		ServerApplication.setLocalBaseDir(localBaseDirPath);
		bossGroup = new NioEventLoopGroup(); // 连接管理
        workerGroup = new NioEventLoopGroup();//工作管理
        serverBootstrap = new ServerBootstrap(); // 引导
        serverBootstrap.group(bossGroup, workerGroup)
         .channel(NioServerSocketChannel.class) //指定线程为TCP连接
         .childHandler(new ServerInitializer())// 管道处理流程
         .option(ChannelOption.SO_BACKLOG, maxBacklog)          //设置事务处理队列长度
         .option(ChannelOption.SO_REUSEADDR, true)//公用端口
         .childOption(ChannelOption.SO_KEEPALIVE, true); // 自动连接测试，长连接，个人理解为tcp心跳
        // 绑定端口，开始接收进来的连接
        serverFuture = serverBootstrap.bind(port); // 绑定端口
        
	}
	
	/**
	 * 启动服务器
	 * @throws InterruptedException
	 */
	public void start() throws InterruptedException {
		serverFuture.channel().closeFuture().addListener(new ChannelFutureListener() {
			
			@Override
			public void operationComplete(ChannelFuture future) throws Exception {
				logger.info("服务关闭");
				
			}
		});
		serverFuture = serverFuture.sync();
		logger.info("服务启动成功！"+serverFuture.channel().localAddress().toString());
	}
	
	/**
	 * 关闭服务器
	 * @throws InterruptedException
	 */
	public void stop() throws InterruptedException {
//		serverFuture.channel().closeFuture().sync();
		serverFuture.channel().close();
		workerGroup.shutdownGracefully();
        bossGroup.shutdownGracefully();
	}
}
